package com.wenfs.demo.controller;

import com.wenfs.demo.entity.MyException;
import com.wenfs.demo.util.VerifyCodeUtil;
import com.wenfs.demo.util.result.ResultEnums;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.UnauthorizedException;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.*;
import java.awt.image.BufferedImage;

/**
 * @author wefashe
 */
@Controller
public class LoginController {

  @GetMapping("/login")
  public String loginGet() {
    boolean isLoginIn = SecurityUtils.getSubject().isAuthenticated();
    return isLoginIn ? "main" : "login";
  }

  @GetMapping("/{page}")
  public String loginGet(@PathVariable("page") String page) {
    return page;
  }

  @PostMapping("/login")
  public String loginPost(HttpServletRequest request, HttpServletResponse response,
                          String userName, String userPass, String captcha,
                          @RequestParam(value = "rememberMe", defaultValue = "0") Integer rememberMe) {
    if (StringUtils.isBlank(userName)) {
      throw new MyException(ResultEnums.ERROR_USERNAME_EMPTY);
    }
    if (StringUtils.isBlank(userPass)) {
      throw new RuntimeException("密码不能为空");
    }
    if (StringUtils.isBlank(captcha)) {
      throw new RuntimeException("验证码不能为空");
    }
    String captchaCode = (String) request.getSession().getAttribute("captcha");
    captcha = captcha.toUpperCase();
    if (!captcha.equals(captchaCode)) {
      throw new RuntimeException("验证码错误");
    }
    Subject user = SecurityUtils.getSubject();
    UsernamePasswordToken token = new UsernamePasswordToken(userName, userPass, captcha);
    token.setRememberMe(1 == rememberMe);
    try {
      user.login(token);
    } catch (UnknownAccountException e) {
      throw new RuntimeException("账号不存在！", e);
    } catch (LockedAccountException e) {
      throw new RuntimeException("账户被锁定！", e);
    } catch (DisabledAccountException e) {
      throw new RuntimeException("账号被禁用！", e);
    } catch (IncorrectCredentialsException e) {
      throw new RuntimeException("密码错误！", e);
    } catch (ExcessiveAttemptsException e) {
      throw new RuntimeException("登录失败次数过多！", e);
    } catch (ExpiredCredentialsException e) {
      throw new RuntimeException("账户已过期！", e);
    } catch (UnauthorizedException e) {
      throw new RuntimeException("账户没有被相应授权！", e);
    } catch (Throwable e) {
      throw new RuntimeException(e.getMessage(), e);
    }
    return "main";
  }


  @GetMapping("/unauth")
  public String unauth() {
    return "unauth";
  }


  /**
   * 获取验证码图片和文本(验证码文本会保存在HttpSession中)
   */
  @RequestMapping("/genCaptcha")
  public void genCaptcha(HttpServletRequest request, HttpServletResponse response) throws Exception {
    //设置页面不缓存
    response.setHeader("Pragma", "no-cache");
    response.setHeader("Cache-Control", "no-cache");
    response.setDateHeader("Expires", 0);
    String captchaNum = VerifyCodeUtil.generateTextCode(VerifyCodeUtil.TYPE_NUM_ONLY, 4, null);
    //将验证码放到HttpSession里面
    request.getSession().setAttribute("captcha", captchaNum);
    System.out.println("本次生成的验证码为[" + captchaNum + "],已存放到HttpSession中");
    //设置输出的内容的类型为JPEG图像
    response.setContentType("image/jpeg");
    BufferedImage bufferedImage = VerifyCodeUtil.generateImageCode(captchaNum, 90, 30, 5, true, Color.WHITE, null, null);
    //写给浏览器
    ImageIO.write(bufferedImage, "JPEG", response.getOutputStream());
  }

}
